package com.caow.composebase.http.interceptor

import com.caow.composebase.event.LoginExpiredEvent
import okhttp3.Interceptor
import okhttp3.Response
import org.greenrobot.eventbus.EventBus
import org.json.JSONObject
import java.nio.charset.StandardCharsets

/**
 * @Author caow
 * 2023/3/20
 */
class TokenInterceptor : Interceptor {
    override fun intercept(chain: Interceptor.Chain): Response {
        val request = chain.request()
        val response = chain.proceed(request)
        val responseBody = response.body
        if (responseBody != null) {
            try {
                val source = responseBody.source()
                source.request(Long.MAX_VALUE)
                val buffer = source.buffer
                val result = buffer.clone().readString(StandardCharsets.UTF_8)
                val jsonObject = JSONObject(result)
                if (jsonObject.has("code")) {
                    val code = jsonObject.getInt("code")
                    if (code == 401) { // 身份过期
                        EventBus.getDefault().post(LoginExpiredEvent())
                    }
                }
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }
        return response
    }
}